<style lang="less">
    @import './edit.less';
</style>

<template>
<Card>
<Form :label-width="80" ref="articleForm" :model="form" :rules="formRules">
    <Row>
        <Col span="22" offset="4">
            <Steps :current="current" style="margin: 1rem 0 3rem 0">
                <Step title="基本信息" content="商品基本信息"></Step>
                <Step title="商品规格" content="商品所有规格参数，库存等..."></Step>
                <Step title="图文详情" content="图文详细描述"></Step>
            </Steps>
        </Col>
    </Row>
    <Row v-show="current==0" type="flex" justify="center" class="code-row-bg">
        <Col span="15">
            <FormItem label="分类：" prop="cate_id" :label-width="100">
                <Select v-model="form.cate_id" @on-change="selCate">
                    <Option v-for="item in cateList" :value="item.cate_id" :key="item.cate_id">{{ item.cate_title }}</Option>
                </Select>
            </FormItem>
            <FormItem label="名称：" prop="product_name" :label-width="100">
                <Input v-model="form.product_name" icon="android-list"/>
                <span style="color: #aaa">不带规格型号</span>
            </FormItem>
            <FormItem label="副标题：" prop="sub_name" :label-width="100">
                <Input v-model="form.sub_name" icon="android-list"/>
                <span style="color: #aaa">一句话简要描述商品卖点</span>
            </FormItem>
            <FormItem label="单价：" prop="unit_money" :label-width="100">
                <Input v-model="form.unit_money" icon="android-list"/>
                <span style="color: #aaa">rmb价格，单位：元</span>
            </FormItem>
            <FormItem label="库存：" prop="stock_num" :label-width="100">
                <Input v-model="form.stock_num" icon="android-list"/>
                <span style="color: #aaa">所有规格预计总库存</span>
            </FormItem>
            <FormItem label="封面图：" prop="cover_img" :label-width="100">
                <Row>
                    <Col span="18"><Input v-model="form.cover_img" icon="image"/><span style="color: #aaa">建议像素为500*400</span></Col>
                    <Col span="6">
                    <Upload
                            ref="upload"
                            action="http://vmallapi.local/adminapi/product/uploadimg"
                            :headers="headers"
                            :data="extraData"
                            name="filedata"
                            :show-upload-list="false"
                            :format="['jpg', 'png', 'jpeg']"
                            :on-format-error="uploadError"
                            :on-success="uploadSuccess"
                    >
                        <Button type="ghost" icon="ios-cloud-upload-outline">上传</Button>
                    </Upload>
                    </Col>
                </Row>
            </FormItem>
            <FormItem label="轮播图：" :label-width="100">
            <div class="demo-upload-list" v-for="item in form.gallery_img">
                <template v-if="item.status === 'finished'">
                    <img :src="item.url">
                    <div class="demo-upload-list-cover">
                        <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                        <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                    </div>
                </template>
                <template v-else>
                    <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                </template>
            </div>
            <Upload
                    multiple
                    ref="upload"
                    name="filedata"
                    :data="extraData"
                    :show-upload-list="false"
                    :default-file-list="uploadList"
                    :on-success="handleSuccess"
                    :format="['jpg','jpeg','png']"
                    :max-size="2048"
                    :on-format-error="handleFormatError"
                    :on-exceeded-size="handleMaxSize"
                    :before-upload="handleBeforeUpload"
                    type="drag"
                    action="http://vmallapi.local/adminapi/product/uploadimg"
                    :headers="headers"
                    style="display: inline-block;width:58px;">
                <div style="width: 58px;height:58px;line-height: 58px;">
                    <Icon type="camera" size="20"></Icon>
                </div>
            </Upload>
            <Modal title="图片预览" v-model="visible">
                <img :src=" imgUrl " v-if="visible" style="width: 100%">
            </Modal>
                <span style="color: #aaa">最多上传5张</span>
            </FormItem>
            <FormItem label="是否显示：" prop="is_show" :label-width="100">
                <Select v-model="form.is_show">
                    <Option v-for="item in isShowList" :value="item.value" :key="item.value">{{ item.name }}</Option>
                </Select>
            </FormItem>
            <FormItem label="是否热销：" prop="is_hot" :label-width="100">
                <Select v-model="form.is_hot">
                    <Option v-for="item in isHotList" :value="item.value" :key="item.value">{{ item.name }}</Option>
                </Select>
            </FormItem>
            <FormItem :label-width="100">
                <Button @click="next" :loading="publishLoading" icon="arrow-right-c" style="width:90px;" type="primary">
                   下一步
                </Button>
            </FormItem>
        </Col>
    </Row>
    <Row v-show="current==1" type="flex" justify="center" class="code-row-bg">
        <Col span="16">
            <FormItem  v-for="(item,index) in specCatsList" :label="item.cat_name" :label-width="100">
                <Input style="width: 100px;" v-model="item.item_input" size="small"></Input>
                <Button type="primary" style="margin-left: -4px;" @click="addItem(index)" size="small">添加</Button>
                <Button type="warning" @click="delItem(index)" size="small">撤销</Button>
                <CheckboxGroup v-model="item.item" @on-change="checkItem">
                    <Checkbox v-for="val in item.item_show" :label="val.title"></Checkbox>
                </CheckboxGroup>
            </FormItem>
            <FormItem v-if="userSpecItemList.length>0" label="规格列表：" :label-width="100">
                <Table
                        border
                        ref="selection"
                        :columns="columns"
                        :data="userSpecItemList"
                        @on-selection-change="selectRow"
                ></Table>
                <span style="color: #aaa">请仔细核对各规格的单价、库存，必须设置一个默认规格</span>
            </FormItem>
            <FormItem :label-width="100">
                <Button @click="prev" :loading="publishLoading" icon="arrow-left-c" style="width:90px;" type="primary">
                    上一步
                </Button>
                <Button @click="next" :loading="publishLoading" icon="arrow-right-c" style="width:90px;" type="primary">
                    下一步
                </Button>
            </FormItem>
        </Col>
    </Row>
    <Row v-show="current==2" type="flex" justify="center" class="code-row-bg">
        <Col span="20">
            <FormItem>
            <p slot="title">
                <Icon type="android-image"></Icon>商品详情
            </p>
            <div class="margin-top-20">
                <textarea id="productEditor" v-model="form.content"></textarea>
            </div>
            </FormItem>
            <FormItem>
                <Button @click="prev" :loading="publishLoading" icon="arrow-left-c" style="width:90px;" type="primary">
                    上一步
                </Button>
                <Button @click="handlePublish" :loading="publishLoading" icon="ios-checkmark" style="width:90px;" type="primary">
                    {{product_id== undefined?'添加':'修改'}}
                </Button>
            </FormItem>
        </Col>
    </Row>
</Form>
</Card>
</template>
<script>
import tinymce from 'tinymce';
import '../../../resource/tinymce/theme';
import '../../../resource/tinymce/zh_CN';
import Util from '../../libs/util';
import Cookies from 'js-cookie';

export default {
    name: 'edit',
    data () {
        return {
            current: 0,
            radio: 0,
            tableSelects: [],
            userSpecItemList: [],
            columns: [
                // {
                //     type: 'selection',
                //     key: 'id',
                //     width: 60,
                //     align: 'center'
                // },
                {
                    title: '默认',
                    key: 'is_default',
                    width: 80,
                    render: (h, params) => {
                        let _this = this;
                        return h('Radio', {
                            props: {
                                size: 'small',
                                value: _this.userSpecItemList[params.index].is_default==0? false: true
                            },
                            on: {
                                'on-change': (event) => {
                                    _this.userSpecItemList.forEach(function (v, i) {
                                        _this.userSpecItemList[i].is_default = 0;
                                    })
                                    _this.userSpecItemList[params.index].is_default = 1;
                                    console.log(_this.userSpecItemList);
                                }
                            }
                        });
                    }
                },
                {
                    title: '规格详情',
                    key: 'spec_name_full'
                },
                {
                    title: '单价（元）',
                    key: 'unit_money',
                    render: (h, params) => {
                        return h('Input', {
                            props: {
                                size: 'small',
                                type: 'text',
                                value: this.userSpecItemList[params.index].unit_money
                            },
                            on: {
                                'on-blur': (event) => {
                                    this.userSpecItemList[params.index].unit_money = event.target.value;
                                }
                            }
                        });
                    }
                },
                {
                    title: '库存',
                    key: 'spec_stock',
                    render: (h, params) => {
                        return h('Input', {
                            props: {
                                size: 'small',
                                type: 'text',
                                value: this.userSpecItemList[params.index].spec_stock
                            },
                            on: {
                                'on-blur': (event) => {
                                    this.userSpecItemList[params.index].spec_stock = event.target.value;
                                }
                            }
                        });
                    }
                },
                {
                    title: '库存预警值',
                    key: 'warn_stock',
                    render: (h, params) => {
                        return h('Input', {
                            props: {
                                size: 'small',
                                type: 'text',
                                value: this.userSpecItemList[params.index].warn_stock
                            },
                            on: {
                                'on-blur': (event) => {
                                    this.userSpecItemList[params.index].warn_stock = event.target.value;
                                }
                            }
                        });
                    }
                },
                {
                    title: '操作',
                    key: 'warn_stock',
                    render: (h, params) => {
                        let _this = this;
                        return h('div', [
                            h('Button', {
                                props: {
                                    size: 'small'
                                },
                                on: {
                                    click: () => {
                                        this.userSpecItemList.splice(params.index, 1);
                                        if(params.row.is_default == 1) {
                                            let flag = false;
                                            _this.userSpecItemList.forEach(function (v, i) {
                                                if(flag == false){
                                                    _this.userSpecItemList[i].is_default = 1;
                                                    flag = true;
                                                }
                                            })
                                        }
                                    }
                                }
                            }, '删除')
                        ]);
                    }
                }
            ],
            form: {
                product_name: '',
                sub_name: '',
                cate_id: '',
                unit_money: '',
                stock_num: '',
                cover_img: '',
                gallery_img: [
                    // {
                    //     'name': 'a42bdcc1178e62b4694c830f028db5c0',
                    //     'url': 'https://o5wwk8baw.qnssl.com/a42bdcc1178e62b4694c830f028db5c0/avatar',
                    //     'status': 'finished'
                    // },
                    // {
                    //     'name': 'bc7521e033abdd1e92222d733590f104',
                    //     'url': 'https://o5wwk8baw.qnssl.com/bc7521e033abdd1e92222d733590f104/avatar',
                    //     'status': 'finished'
                    // }
                ],
                is_show: 1,
                is_hot: 1,
                content: ''
            },
            formRules: {
                cate_id: [
                    { type: 'number', required: true, message: '必须选择一个分类', trigger: 'blur' }
                ],
                product_name: [
                    { required: true, message: '名称不能为空', trigger: 'blur' }
                ],
                unit_point: [
                    { required: true, message: '必须设置单价', trigger: 'blur' }
                ],
                stock_num: [
                    { required: true, message: '请确认库存', trigger: 'blur' }
                ],
                is_show: [
                    { type: 'number', required: true, message: '请选择显示状态', trigger: 'blur' }
                ],
                is_hot: [
                    { type: 'number', required: true, message: '请选择热销状态', trigger: 'blur' }
                ],
                cover_img: [
                    { required: true, message: '必须上传或输入图片地址', trigger: 'blur' }
                ],
                gallery_img: [
                    { required: true, message: '必须上传或输入轮播图', trigger: 'blur' }
                ]
            },
            isShowList: [{value: 1, 'name': '是'}, {value: 0, 'name': '否'}],
            isShowList1: [{value: 1, 'name': '是'}, {value: 0, 'name': '否'}],
            isHotList: [{value: 1, 'name': '是'}, {value: 0, 'name': '否'}],
            cateList: [],
            publishLoading: false,
            uploadCoverImg: {type: 'cover'},
            product_id: this.$route.params.product_id,
            action: '',
            imgUrl: '',
            visible: false,
            uploadList: [
                // {
                //     'name': 'a42bdcc1178e62b4694c830f028db5c0',
                //     'url': 'https://o5wwk8baw.qnssl.com/a42bdcc1178e62b4694c830f028db5c0/avatar',
                //     'status': 'finished'
                // },
                // {
                //     'name': 'bc7521e033abdd1e92222d733590f104',
                //     'url': 'https://o5wwk8baw.qnssl.com/bc7521e033abdd1e92222d733590f104/avatar',
                //     'status': 'finished'
                // }
            ],
            headers: {
                'X-AUTH-TOKEN': Cookies.get('token')
            },
            extraData: {type: 'cover'},
            specCatsList: []
        };
    },
    methods: {
        selectRow (selection, row) {
            this.tableSelects = selection;
        },
        next () {
            let _this = this;
            this.$refs.articleForm.validate((valid) => {
                if (valid) {
                    if (this.form.gallery_img.length == 0) {
                        this.$Message.warning('必须上传轮播图');
                        return;
                    }
                    if (this.current == 1 && _this.userSpecItemList.length <= 0) {
                        this.$Message.warning('必须设置一个默认规格');
                        return ;
                    }
                    this.current += 1;
                }
            });
        },
        prev () {
            this.current -= 1;
        },
        handlePublish () {
            let _this = this;
            this.$refs.articleForm.validate((valid) => {
                if (valid) {
                    if(this.form.gallery_img.length == 0) {
                        this.$Message.error('必须上传轮播图');
                        return;
                    }
                    const content = tinymce.get('productEditor').getBody().innerHTML;
                    // const content = tinymce.get('articleEditor').getContent({'format': 'raw'});
                    if (content == '<p><br data-mce-bogus="1"></p>') {
                        this.$Message.error('必须编辑商品详情');
                        return;
                    }
                    this.form.content = content;
                    let url, params;
                    if (this.product_id > 0) {
                        url = `/adminapi/product/edit`;
                        params = {
                            ...this.form,
                            product_id: this.product_id
                        };
                    } else {
                        url = `/adminapi/product/add`;
                        params = this.form;
                    }
                    var spec_items = this.allItem(1);
                    var p = {
                        'product': params,
                        'spec_items': spec_items,
                        'product_specs': _this.userSpecItemList
                    }
                    Util.ajax.post(url, p).then(response => {
                        if(response.data.code == 0) {
                            this.$router.push({
                                name: 'product'
                            });
                            this.$Message.success(response.data.msg);
                        } else {
                            this.$Message.error(response.data.msg);
                        }
                    });
                }
            });
        },
        uploadError () {
            this.$Message.error('文件格式错误，选择其他文件重试');
        },
        uploadSuccess (response, file) {
            if(response.code == 0) {
                // this.$refs.upload.clearFiles(); //清空上传列表
                this.form.cover_img = response.data;
            }else {
                this.$Message.error('上传失败');
            }
        },
        getProductDetail (product_id) {
            Util.ajax.post(`/adminapi/product/detail`, {product_id: product_id, is_admin: 1}).then(response => {
                if(response.data.code == 0) {
                    const detail = response.data.data;
                    this.form = {
                        product_name: detail.product_name,
                        sub_name: detail.sub_name,
                        cate_id: detail.cate_id,
                        unit_point: detail.unit_point,
                        stock_num: detail.stock_num.toString(),
                        cover_img: detail.cover_img,
                        gallery_img: detail.gallery_img,
                        is_show: detail.is_show,
                        is_hot: detail.is_hot,
                        content: detail.content
                    };
                    tinymce.get('productEditor').setContent(this.form.content);
                }else {
                    this.$Message.error(response.data.errMsg);
                }
            });
        },
        handleGoback () {
            // this.$router.go(-1);
            this.$router.push({
                name: 'product',
                params: {page: this.$route.params.page}
            });
        },
        handleView (url) {
            this.imgUrl = url;
            this.visible = true;
        },
        handleRemove (file) {
            // const fileList = this.$refs.upload.fileList;
            // this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
            const fileList = this.form.gallery_img;
            this.form.gallery_img.splice(fileList.indexOf(file), 1);
        },
        handleSuccess (res, file, filelist) {
            file.url = res.data;
            if( filelist.length>5 ) {
               filelist = filelist.slice(0, 5);
                this.$Notice.warning({
                    title: '最多上传5张图片..'
                });
            }
            this.form.gallery_img = filelist;
        },
        handleFormatError (file) {
            this.$Notice.warning({
                title: '文件格式错误',
                desc: '必须上传jpg、png。'
            });
        },
        handleMaxSize (file) {
            this.$Notice.warning({
                title: '文件大小超出限制',
                desc: '文件大小超出限制, 必须小于2M.'
            });
        },
        handleBeforeUpload () {
            const check1 = this.form.gallery_img.length < 5;
            if (!check1) {
                this.$Notice.warning({
                    title: '最多上传5张图片.'
                });
                return false;
            }
            return true;
        },

        getCatelist () {
            Util.ajax.post(`/adminapi/product/catelist`, { pageSize: 100 }).then(response => {
                this.cateList = response.data.data.list;
            });
        },
        selCate () {
            Util.ajax.post(`/adminapi/product/speccatslist`, { pageSize: 100,cate_id: this.form.cate_id }).then(response => {
                this.specCatsList = response.data.data.list;
                if (this.specCatsList.length <= 0) {
                    this.$Modal.confirm({
                        title: '提示',
                        content: '该分类还未添加属性，无法进行一部操作！',
                        okText: '去添加',
                        onOk: () => {
                            this.$router.push({
                                name: 'speccats'
                            });
                        },
                        onCancel: () => {
                        }
                    });
                }
            });
        },
        addItem (index) {
            var value = this.specCatsList[index].item_input;
            if (!value) {
                alert('规格不能为空');
                return;
            }
            var allItemShow = this.allItemShow();
            var check = allItemShow.indexOf(value);
            if (check != '-1') {
                alert('存在相同属性的规格');
                this.specCatsList[index].item_input = '';
                return;
            }
            this.specCatsList[index].item_show.push({title: value});
            this.specCatsList[index].item_input = '';
        },
        delItem(index) {
            this.specCatsList[index].item_show.splice(-1, 1);
        },
        checkItem (value) {
            var items = this.allItem();
            var rs = this.descartes(items);
            let temp = [];
            rs.forEach(function (v, i) {
                if ((Array.isArray(v))) {
                    var spec_name_full = v.join(' ');
                } else {
                    var spec_name_full = v;
                }
                var obj = {'id': i, spec_name_full: spec_name_full, unit_money: 1, spec_stock: 1, warn_stock: 1, is_default: 0};
                temp.push(obj);
            })
            temp[0].is_default = 1;
            this.userSpecItemList = temp;
        },
        //所有规格值
        allItem (post) {
            let items = [];
            this.specCatsList.forEach(function (v, i) {
                let temp = [];
                v.item.forEach(function (vv) {
                    temp.push(vv);
                })
                if (temp.length > 0) {
                    if (post == 1) {
                        items[v.cat_id] = temp;
                    } else {
                        items.push(temp);
                    }
                }

            });
            return items;
        },
        //所有规格候选值
        allItemShow () {
            let itemShow = []
            this.specCatsList.forEach(function (v, i) {
                v.item_show.forEach(function (v) {
                    itemShow.push(v.title);
                });
            });
            return itemShow;
        },
        descartes (items) {
            // var args = [['国行', '港版'], ['16G', '64G'], ['白色', '黑色', '红色']];
            // var args = [['国行', '港版'], ['16G', '64G'], ['白色', '黑色', '红色']];
            var args = items;
            var rs   = [];

            // A. 校验并转换为JS数组
            for (var i = 0; i < args.length; i++) {
                if (!Array.isArray(args[i])) {
                    return false;  // 参数必须为数组
                }
            }

            // 两个笛卡尔积换算
            var bothDescartes = function (m, n){
                var r = []
                for (var i = 0; i < m.length; i++) {
                    for (var ii = 0; ii < n.length; ii++) {
                        var t = [];
                        if (Array.isArray(m[i])) {
                            t = m[i].slice(0);  //此处使用slice目的为了防止t变化，导致m也跟着变化
                        } else {
                            t.push(m[i]);
                        }
                        t.push(n[ii]);
                        r.push(t);
                    }
                }
                return r;
            }

            // 多个笛卡尔基数换算
            for (var i = 0; i < args.length; i++) {
                if (i == 0) {
                    rs = args[i];
                } else {
                    rs = bothDescartes(rs, args[i]);
                }
            }

            return rs;
        }
    },
    computed: {
    },
    mounted () {
        this.getCatelist();
        tinymce.init({
            skin_url: '/resource/tinymce/skins/lightgray',
            selector: '#productEditor',
            branding: false,
            elementpath: false,
            height: 600,
            language: 'zh_CN',
            menubar: 'edit insert view format table tools',
            theme: 'modern',
/*            plugins: [
                'advlist autolink lists link image charmap print preview hr anchor pagebreak imagetools',
                'searchreplace visualblocks visualchars code fullpage',
                'insertdatetime nonbreaking save table contextmenu directionality',
                'emoticons paste textcolor colorpicker textpattern imagetools codesample'
            ],*/
            external_plugins: {
                'image': '/resource/tinymce/plugins/image/plugin.min.js',
                'link': '/resource/tinymce/plugins/link/plugin.min.js',
                'preview': '/resource/tinymce/plugins/preview/plugin.min.js',
                'pagebreak': '/resource/tinymce/plugins/pagebreak/plugin.min.js',
                'textcolor': '/resource/tinymce/plugins/textcolor/plugin.min.js'
            },
            toolbar: 'newnote print preview | undo redo | insert | styleselect | forecolor backcolor bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image emoticons',
            image_title: true,
            automatic_uploads: true,
            file_picker_types: 'image',
            file_picker_callback: function(cb, value, meta) {
                let input = document.createElement('input');
                input.setAttribute('type', 'file');
                input.setAttribute('accept', 'image/*');
                input.onchange = function() {
                    let file = this.files[0];

                    let reader = new FileReader();
                    reader.onload = function () {
                        Util.ajax.post(`/adminapi/product/uploadimg`, reader.result).then(response => {
                            if (response.data.code == 0) {
                                cb(response.data.data.url, { title: file.name });
                            }else {
                                alert('上传失败，请重试');
                            }
                        });
                    };
                    reader.readAsDataURL(file);
                };

                input.click();
            },
            image_advtab: true,
            table_default_styles: {
                width: '100%',
                borderCollapse: 'collapse'
            }
        });
        if (this.product_id) {
            this.getProductDetail(this.product_id);
        }
    },
    destroyed () {
        tinymce.get('productEditor').destroy();
    }
};
</script>
<style>
    .demo-upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
